package org.koyad.portal.tags.piston;

import java.util.Map;

import org.koyad.portal.annotations.TagCordinates;
import org.koyad.portal.annotations.TagType;
import org.koyad.portal.api.BaseAction;
import org.koyad.portal.constants.FrameworkConstants;
import org.koyad.portal.context.PistonContext;
import org.koyad.portal.tags.AbstractTag;
import org.koyad.portal.utils.LogUtils;

@TagCordinates (
	uri = FrameworkConstants.PORTAL_NAMESPACE,
	localName = "action",
	type = TagType.NOBODY
)
public class ActionTag extends AbstractTag {
	
	private static final LogUtils LOGGER = LogUtils.getLogger(ActionTag.class);
	
	@Override
	public void postInit() {
		PistonContext pistonCtx = PistonContext.getContext();
		Map<String, String> actions = (Map<String, String>) pistonCtx.getApplication().getAttribute(FrameworkConstants.PISTON_ACTIONS);
		String action = actions.get(getAttributeValue("name"));
		
		try {
			Class actionClass = Class.forName(action);
			BaseAction bAction = (BaseAction)actionClass.newInstance();
			PistonContext.getContext().getViewRoot().setCurrentTag(this);
			bAction.execute();
		} catch (ClassNotFoundException e) {
			LOGGER.logException(e);
		} catch (InstantiationException e) {
			LOGGER.logException(e);
		} catch (IllegalAccessException e) {
			LOGGER.logException(e);
		}
	}
	
	@Override
	public void render() {
		super.renderBody();
	}
}
